package cn.edu.lingnan.lsqn.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.cdahua.basic.model.Pager;
import cn.cdahua.basic.model.SystemContext;
import cn.edu.lingnan.lsqn.model.LsqnException;
import cn.edu.lingnan.lsqn.model.User;
import cn.edu.lingnan.lsqn.service.IUserService;

@Controller
@RequestMapping("/system")
public class SystemController {

	@Autowired
	private IUserService userService;

	@RequestMapping("/")
	public String index(Model model) {
		return "system/system";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(@RequestParam("iconF") MultipartFile iconF, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain;charset=utf-8");
		// 保存icon文件
		String realPath = SystemContext.getRealPath();
		if (realPath == null || realPath.equals(""))
			return;
		String path = realPath + "/upload/icon/";
		File iconFile = new File(path);
		if (!iconFile.exists())
			iconFile.mkdirs();
		String ext = FilenameUtils.getExtension(iconF.getOriginalFilename());
		String newFileName = String.valueOf(new Date().getTime() + "." + ext);
		path = path + newFileName;
		FileUtils.copyInputStreamToFile(iconF.getInputStream(), new File(path));
		resp.getWriter().write("/resources/upload/icon/" + newFileName);
	}

	@RequestMapping("/user/list/{r_id}")
	public String userList(@PathVariable int r_id, Model model) {
		Pager<User> users = userService.listUserByRole(r_id);
		model.addAttribute("datas", users);
		model.addAttribute("r_id", r_id);
		return "comm/userlist";
	}

	@RequestMapping("/user/list/{r_id}/{id}/update")
	public String userUpdate(@PathVariable int id, @PathVariable int r_id) {
		User u = userService.load(id);
		int status = u.getStatus() == 0 ? 1 : 0;
		u.setStatus(status);
		userService.update(u);
		return "redirect:/system/user/list/" + r_id;
	}

	@RequestMapping("/user/list/{r_id}/{id}/reset")
	public String userReset(@PathVariable int id, @PathVariable int r_id) {
		User u = userService.load(id);
		u.setPassword("000000");
		userService.update(u);
		return "redirect:/system/user/list/" + r_id;
	}

	@RequestMapping(value = "/user/add", method = RequestMethod.GET)
	public String userAdd() {
		return "user/add";
	}

	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	public String userAdd(User user, @RequestParam("gid") String[] gid, @RequestParam("rid") String[] rid) {
		Integer[] g_id = new Integer[gid.length];
		Integer[] r_id = new Integer[rid.length];
		for (int i = 0; i < gid.length; i++) {
			g_id[i] = Integer.parseInt(gid[i]);
		}
		for (int i = 0; i < rid.length; i++) {
			r_id[i] = Integer.parseInt(rid[i]);
		}
		userService.add(user, g_id, r_id);
		return "redirect:/system/user/list/1";
	}

	@RequestMapping(value = "/user/update/{id}", method = RequestMethod.GET)
	public String userUpdate(Model model, @PathVariable int id) {
		model.addAttribute("user", userService.load(id));
		return "user/update";
	}

	@RequestMapping(value = "/user/update/{id}", method = RequestMethod.POST)
	public String userUpdate(HttpSession session, User u, @PathVariable int id) {
		User user = userService.load(id);
		user.setEmail(u.getEmail());
		if (u.getIcon() != null && !(u.getIcon()).equals("")) {
			user.setIcon(u.getIcon());
		}
		user.setNickname(u.getNickname());
		user.setUsername(u.getUsername());
		userService.update(user);
		session.setAttribute("loginUser", user);
		return "redirect:/system/user/list/1";
	}
	
	@RequestMapping(value = "/user/updatepsw", method = RequestMethod.GET)
	public String userUpdate() {
		return "user/updatepsw";
	}
	@RequestMapping(value = "/user/updatepsw", method = RequestMethod.POST)
	public String userUpdate(@RequestParam String password,@RequestParam String oldpassword,HttpSession session) {
		User sessionU = (User)session.getAttribute("loginUser");
		if(!oldpassword.equals(sessionU.getPassword())){
			throw new LsqnException("旧密码不正确");
		} else{
			User databaseU = userService.load(sessionU.getId());
			databaseU.setPassword(password);
			userService.update(databaseU);
			return "user/updatepsw";
		}
	}
	@RequestMapping(value = "/loginuser/update", method = RequestMethod.GET)
	public String loginUserUpdate(Model model, HttpSession session) {
		User loginUser = (User) session.getAttribute("loginUser");
		model.addAttribute("user", userService.load(loginUser.getId()));
		return "user/update";
	}
	
	@RequestMapping(value = "/loginuser/update", method = RequestMethod.POST)
	public String loginUserUpdate(HttpSession session, User u) {
		User loginUser = (User) session.getAttribute("loginUser");
		User user = userService.load(loginUser.getId());
		user.setEmail(u.getEmail());
		if (u.getIcon() != null && !(u.getIcon()).equals("")) {
			user.setIcon(u.getIcon());
		}
		user.setNickname(u.getNickname());
		user.setUsername(u.getUsername());
		userService.update(user);
		session.setAttribute("loginUser", user);
		return "redirect:/index";
	}
	
	@RequestMapping(value = "/loginuser/updatepsw", method = RequestMethod.GET)
	public String loginUserUpdatepsw() {
		return "user/updatepsw";
	}
	@RequestMapping(value = "/loginuser/updatepsw", method = RequestMethod.POST)
	public String loginUserUpdatepsw(@RequestParam String password,@RequestParam String oldpassword,HttpSession session) {
		User sessionU = (User)session.getAttribute("loginUser");
		if(!oldpassword.equals(sessionU.getPassword())){
			throw new LsqnException("旧密码不正确");
		} else{
			User databaseU = userService.load(sessionU.getId());
			databaseU.setPassword(password);
			userService.update(databaseU);
			return "user/updatepsw";
		}
	}
	@RequestMapping("/setting")
	public String setting(Model model){
		String path = this.getClass().getClassLoader().getResource("").getPath();
		try(InputStream is = new FileInputStream(path+"admin.properties")) {
			Properties p = new Properties();
			p.load(is);
			String email = p.getProperty("admin");
			model.addAttribute("email", email);
		} catch (IOException | NullPointerException e) {
			e.printStackTrace();
		}
		return "system/setting";
	}
	@RequestMapping(value="/setting/email",method=RequestMethod.POST)
	public String email(@RequestParam String email){
		Properties p = new Properties();
		p.setProperty("admin", email);
		String path = this.getClass().getClassLoader().getResource("").getPath();
		try(OutputStream out = new FileOutputStream(path+"admin.properties");){
			p.store(out, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return "redirect:/system/setting";
	}
	
	
}
